<template>
  <div class="order-dashboard">
    <!-- 顶部导航栏 -->
    <header class="header">
      <div class="header-container">
        <!-- 品牌与统计 -->
        <div class="branding">
          <img src="https://picsum.photos/id/1079/120/40" alt="Logo" class="logo">
          <div class="stats">
            <div class="stat">
              <span class="icon">📊</span>
              <div class="value">总销售量</div>
              <div class="number">{{ calculateTotalQuantity() }}</div>
            </div>
            <div class="stat">
              <span class="icon">💴</span>
              <div class="value">总销售额</div>
              <div class="number">¥{{ calculateAllTotal() }}</div>
            </div>
          </div>
        </div>

        <!-- 搜索与筛选 -->
        <div class="search-filter">
          <div class="search-box">
            <input
              type="text"
              v-model="searchKey"
              placeholder="搜索订单号/收货人"
              class="search-input"
            >
            <button class="search-btn">
              <i class="fa fa-search"></i>
            </button>
          </div>

          <div class="filter-dropdown">
            <span class="filter-text">筛选状态：{{ getStatusText(statusFilter) }}</span>
            <ul class="filter-options">
              <li
                v-for="(state, key) in statusMap"
                :key="key"
                @click="statusFilter = key"
                :class="{ active: statusFilter === key }"
              >
                <span :style="{ background: state.color }" class="status-dot"></span>
                {{ state.text }}
              </li>
            </ul>
          </div>
        </div>
      </div>
    </header>

    <!-- 订单列表 -->
    <main class="order-list-container">
      <div
        v-for="(order, index) in filteredOrders"
        :key="order.orderId"
        class="order-card"
        @click="toggleExpand(index)"
        @mouseenter="hoverIndex = index"
        @mouseleave="hoverIndex = -1"
      >
        <!-- 订单头部 -->
        <div class="order-header">
          <div class="order-info">
            <h3 class="order-id">#{{ order.merchantName }}</h3>
            <p class="order-meta">
              <span class="icon">🕒</span> {{ order.createdAt.slice(0, 16) }}
              <span class="icon">📍</span> {{ getAddressLevelTwo(order) }}
            </p>
          </div>

          <!-- 收缩状态下的商品图片展示 - 带滑动功能 -->
          <div class="order-product-thumbs-container">
            <div class="order-product-thumbs" v-if="order.productVo && order.productVo.length > 0">
              <div
                v-for="(product, pIndex) in order.productVo"
                :key="pIndex"
                class="product-thumb"
                v-show="product.imageLoaded !== false"
              >
                <img
                  :src="product.imageUrl || 'https://picsum.photos/50/50?random=' + pIndex"
                  alt="product.name"
                  class="thumb-image"
                  @load="product.imageLoaded = true"
                  @error="product.imageLoaded = false"
                >
              </div>
            </div>
          </div>

          <!-- 动态状态标签 -->
          <div class="status-badge" :style="{ background: getStatusColor(order.status) }">
            <span class="status-text">{{ getStatusText(order.status) }}</span>
            <span class="status-marker"></span>
          </div>
        </div>

        <!-- 展开内容 -->
        <transition name="slide">
          <div v-show="expandedIndex === index" class="order-details">
            <!-- 收货信息 -->
            <div class="section address-section" v-if="order.shippingAddress">
              <h4 class="section-title">
                <span class="icon">📮</span> 收货地址
              </h4>
              <address class="full-address">
                {{ getFullAddress(order.shippingAddress) }}<br>
                <strong>收货人：</strong> {{ order.shippingAddress.name || '未填写' }}<br>
                <strong>电话：</strong> {{ order.shippingAddress.phonenumber || '未填写' }}
              </address>
            </div>
            <div class="section address-section" v-else>
              <h4 class="section-title">
                <span class="icon">📮</span> 收货地址
              </h4>
              <p class="text-red-500">收货地址信息缺失</p>
            </div>

            <!-- 商品列表 -->
            <div class="section products-section">
              <h4 class="section-title">
                <span class="icon">🛍️</span> 购买商品 ({{ order.productVo.length }})
              </h4>
              <div class="products-grid">
                <div
                  v-for="(product, pIndex) in order.productVo"
                  :key="pIndex"
                  class="product-item"
                  @mouseenter="hoverProductIndex = pIndex"
                  @mouseleave="hoverProductIndex = -1"
                >
                  <div class="product-image-container">
                    <img
                      :src="product.imageUrl"
                      alt="product.name"
                      class="product-image"
                      :class="{ 'scale-hover': hoverProductIndex === pIndex }"
                    >
                  </div>
                  <div class="product-details">
                    <h5 class="product-name">{{ product.name }}</h5>
                    <p class="product-sku">SKU: {{ product.sku }}</p>
                    <div class="product-quantity">
                      <span class="label">数量:</span> {{ product.quantity }}
                    </div>
                    <div class="product-price">
                      <span class="label">单价:</span> ¥{{ product.price }}
                    </div>
                    <div class="product-subtotal">
                      <span class="label">小计:</span> <strong>¥{{ product.price * product.quantity }}</strong>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 价格摘要 -->
            <div class="section price-section">
              <h4 class="section-title">
                <span class="icon">💰</span> 价格摘要
              </h4>
              <div class="price-details">
                <div class="price-row">
                  <span class="label">商品总价:</span>
                  <span class="value">¥{{ calculateTotal(order) }}</span>
                </div>
                <div class="price-row">
                  <span class="label">运费:</span>
                  <span class="value">¥{{ order.shippingFee }}</span>
                </div>
                <div class="price-row total">
                  <span class="label">应付总额:</span>
                  <span class="value">¥{{ calculateOrderTotal(order) }}</span>
                </div>
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="section actions-section">
              <button
                class="action-btn print-btn"
                @click.stop="handlePrint(order.orderId)"
              >
                <i class="fa fa-print"></i> 打印订单
              </button>
              <button
                class="action-btn view-btn"
                @click.stop="handleViewDetails(order.orderId)"
              >
                <i class="fa fa-eye"></i> 查看详情
              </button>
            </div>
          </div>
        </transition>

      </div>
    </main>
    <el-dialog :visible.sync="dialogVisible" :modal="false" :close-on-escape="false">
      <merchant-order :id="currentOrder" @back="parentMethod" :status="status" />
    </el-dialog>
  </div>
</template>

<script>
import { getOrderList } from '@/api/list/order'
import MerchantOrder from '@/views/list/merchan/merchantOrder.vue'

export default {
  components: { MerchantOrder },
  data() {
    return {
      dialogVisible: false,
      status:1,
      searchKey: '',
      statusFilter: '',
      expandedIndex: -1,
      hoverIndex: -1,
      hoverProductIndex: -1,
      currentOrder:null,
      queryParams: {},
      orders: [],
      statusMap: {
        '1': { text: '待付款', color: '#ff9800' },
        '2': { text: '已付款', color: '#2196f3' },
        '3': { text: '待发货', color: '#4caf50' },
        '4': { text: '已发货', color: '#607d8b' },
        '5': { text: '已完成', color: '#f44336' },
        '6': { text: '已取消', color: '#ffeb3b' },
        '': { text: '全部状态', color: '#9e9e9e' }
      }
    }
  },
  computed: {
    filteredOrders() {
      return this.orders.filter(order => {
        // 状态筛选
        if (this.statusFilter && order.status !== this.statusFilter) {
          return false
        }

        // 搜索筛选
        if (this.searchKey) {
          const searchLower = this.searchKey.toLowerCase()
          return order.orderId.toString().includes(searchLower) ||
            (order.shippingAddress && order.shippingAddress.name && order.shippingAddress.name.toLowerCase().includes(searchLower))
        }

        return true
      })
    }
  },
  methods: {
    parentMethod() {
      this.dialogVisible = false
    },
    // 获取订单列表
    fetchOrderList() {
      getOrderList().then(response => {
        this.orders = response.data|| []
        // 确保状态值转换为字符串以匹配statusMap
        this.orders = this.orders.map(order => ({
          ...order,
          status: String(order.status)
        }))
      })
        .catch(error => {
          console.error('获取订单列表失败:', error)
          this.orders = [] // 确保orders始终是数组
        })
    },
    toggleExpand(index) {
      this.expandedIndex = this.expandedIndex === index ? -1 : index
    },
    getStatusText(status) {
      return this.statusMap[status]?.text || '未知状态'
    },
    getStatusColor(status) {
      return this.statusMap[status]?.color || '#9e9e9e'
    },
    calculateTotal(order) {
      return (order.productVo || []).reduce((sum, product) => {
        return sum + (parseFloat(product.price) * parseInt(product.quantity))
      }, 0)
    },
    handlePrint(orderId) {
      console.log(`打印订单: ${orderId}`)
      // 实际应用中可以调用浏览器打印功能
    },
    handleViewDetails(orderId) {
      this.currentOrder = orderId;
      this.dialogVisible = true;
      console.log(`查看订单详情: ${orderId}`)
      // 实际应用中可以跳转到订单详情页
    },
    // 计算订单应付总额
    calculateOrderTotal(order) {
      return (parseFloat(order.totalPrice) - parseFloat(order.shippingFee)).toFixed(2)
    },
    // 计算所有订单的总金额
    calculateAllTotal() {
      return this.orders.reduce((total, order) => {
        return total + parseFloat(order.totalPrice || 0)
      }, 0).toFixed(2)
    },
    // 计算所有订单的商品总数量
    calculateTotalQuantity() {
      return this.orders.reduce((total, order) => {
        return total + parseInt(order.totalNumber || 0)
      }, 0)
    },
    // 安全获取地址二级名称
    getAddressLevelTwo(order) {
      if (!order.shippingAddress) return '地址信息缺失'
      return order.shippingAddress.levelTwoName || '未填写'
    },
    // 安全获取完整地址
    getFullAddress(address) {
      return [
        address.provinceName,
        address.cityName,
        address.areaName,
        address.address
      ].filter(part => part).join(' ')
    }
  },
  mounted() {
    this.fetchOrderList()
  }
}
</script>

<style scoped>
/* 全局样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Inter', sans-serif;
}

body {
  background-color: #f8f9fa;
  color: #333;
}

/* 头部样式 */
.header {
  background-color: #fff;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  padding: 20px 0;
  margin-bottom: 25px;
}

.header-container {
  max-width: 1000px;
  margin: 0 auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.branding {
  display: flex;
  align-items: center;
}

.logo {
  height: 40px;
  margin-right: 30px;
}

.stats {
  display: flex;
}

.stat {
  margin-right: 30px;
  text-align: center;
}

.stat .icon {
  font-size: 24px;
  display: block;
  margin-bottom: 5px;
  color: #555;
}

.stat .value {
  font-size: 14px;
  color: #777;
}

.stat .number {
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.search-filter {
  display: flex;
  align-items: center;
  gap: 20px;
}

.search-box {
  display: flex;
  align-items: center;
  border: 1px solid #ddd;
  border-radius: 25px;
  overflow: hidden;
  padding: 5px;
  width: 300px;
}

.search-input {
  flex-grow: 1;
  border: none;
  padding: 8px 15px;
  outline: none;
  font-size: 14px;
}

.search-btn {
  background: none;
  border: none;
  padding: 8px 15px;
  color: #3498db;
  cursor: pointer;
  transition: background 0.2s;
}

.search-btn:hover {
  background: #f0f0f0;
  border-radius: 50%;
}

.filter-dropdown {
  position: relative;
  cursor: pointer;
  padding: 10px 15px;
  border-radius: 25px;
  background-color: #f8f9fa;
  transition: background 0.2s;
}

.filter-dropdown:hover {
  background-color: #f0f0f0;
}

.filter-options {
  position: absolute;
  top: 100%;
  right: 0;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
  padding: 10px 0;
  z-index: 10;
  min-width: 200px;
  display: none;
}

.filter-dropdown:hover .filter-options {
  display: block;
}

.filter-options li {
  padding: 8px 20px;
  list-style: none;
  display: flex;
  align-items: center;
  transition: background 0.2s;
}

.filter-options li:hover {
  background-color: #f8f9fa;
}

.filter-options li.active {
  font-weight: 600;
}

.status-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 10px;
}

/* 订单列表样式 */
.order-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  max-height: 600px; /* 增加最大高度 */
  overflow-y: auto;
  scrollbar-width: none; /* 隐藏Firefox滚动条 */
  -ms-overflow-style: none; /* 隐藏IE/Edge滚动条 */
}

.order-list-container::-webkit-scrollbar {
  display: none; /* 隐藏Chrome/Safari滚动条 */
}

.order-card {
  background-color: #fff;
  border-radius: 15px;
  margin-bottom: 20px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s, box-shadow 0.2s;
}

.order-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
}

.order-info .order-id {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 5px;
}

.order-meta {
  font-size: 14px;
  color: #777;
}

.order-meta .icon {
  margin-right: 5px;
}

.status-badge {
  padding: 8px 15px;
  border-radius: 20px;
  font-weight: 500;
  font-size: 14px;
  display: flex;
  align-items: center;
  position: relative;
  overflow: hidden;
}

.status-badge::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  animation: slideShine 3s infinite;
}

.status-marker {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 8px;
  background-color: white;
}

@keyframes slideShine {
  0% {
    left: -100%;
  }
  20% {
    left: 100%;
  }
  100% {
    left: 100%;
  }
}

.order-details {
  padding: 20px;
}

.section {
  margin-bottom: 20px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.section:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #555;
  margin-bottom: 15px;
}

.section-title .icon {
  margin-right: 10px;
  width: 20px;
  text-align: center;
}

.full-address {
  line-height: 1.8;
  font-style: normal;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 15px;
}

.product-item {
  display: flex;
  background-color: #f8f9fa;
  border-radius: 10px;
  overflow: hidden;
  transition: transform 0.2s;
}

.product-item:hover {
  transform: translateY(-2px);
}

.product-image-container {
  width: 100px;
  height: 100px;
  overflow: hidden;
  background-color: #fff;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: transform 0.3s;
}

.scale-hover {
  transform: scale(1.05);
}

.product-details {
  flex-grow: 1;
  padding: 15px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.product-name {
  font-size: 15px;
  font-weight: 500;
  margin-bottom: 5px;
}

.product-sku {
  font-size: 13px;
  color: #777;
  margin-bottom: 5px;
}

.product-quantity,
.product-price,
.product-subtotal {
  font-size: 14px;
  display: flex;
  align-items: center;
}

.product-quantity .label,
.product-price .label,
.product-subtotal .label {
  color: #777;
  width: 45px;
  display: inline-block;
}

.product-subtotal {
  font-weight: 600;
  color: #e74c3c;
}

.price-details {
  max-width: 350px;
}

.price-row {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  font-size: 15px;
}

.price-row.total {
  font-weight: 600;
  color: #27ae60;
  border-top: 1px solid #eee;
  margin-top: 8px;
  padding-top: 12px;
}

.actions-section {
  display: flex;
  gap: 15px;
}

.action-btn {
  padding: 10px 20px;
  border-radius: 25px;
  border: none;
  background-color: #f0f0f0;
  color: #555;
  cursor: pointer;
  transition: background 0.2s;
  display: flex;
  align-items: center;
}

.action-btn:hover {
  background-color: #e0e0e0;
}

.action-btn .fa {
  margin-right: 8px;
}

.print-btn {
  background-color: #3498db;
  color: white;
}

.print-btn:hover {
  background-color: #2980b9;
}

.view-btn {
  background-color: #2ecc71;
  color: white;
}

.view-btn:hover {
  background-color: #27ae60;
}

/* 展开/收起动画 */
.slide-enter-active,
.slide-leave-active {
  transition: all 0.3s ease;
  overflow: hidden;
}

.slide-enter-from,
.slide-leave-to {
  max-height: 0;
  opacity: 0;
}

.slide-enter-to,
.slide-leave-from {
  max-height: 1000px;
  opacity: 1;
}

/* 添加收缩状态下图片展示的样式 */
.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.order-info {
  flex: 1;
  margin-right: 15px;
}

.order-product-thumbs {
  display: flex;
  align-items: center;
}

.product-thumb {
  margin-left: 8px;
  position: relative;
}

.product-thumb:first-child {
  margin-left: 0;
}

.thumb-image {
  width: 40px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #eee;
}

.more-products {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 40px;
  height: 40px;
  background-color: #f5f5f5;
  color: #666;
  border-radius: 4px;
  border: 1px solid #eee;
  margin-left: 8px;
  font-size: 12px;
}

/* 商品图片滑动容器 */
.order-product-thumbs-container {
  margin-right: 20px; /* 添加右侧间距 */
  overflow-x: auto;
  white-space: nowrap;
  max-width: 400px;
  padding: 5px 0;
  scrollbar-width: thin;
  scrollbar-color: #ccc #f0f0f0;
}

.order-product-thumbs-container::-webkit-scrollbar {
  height: 4px;
}

.order-product-thumbs-container::-webkit-scrollbar-track {
  background: #f0f0f0;
  border-radius: 4px;
}

.order-product-thumbs-container::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 4px;
}

/* 优化订单头部布局 */
.order-header {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #eee;
}

.order-info {
  flex: 1;
  min-width: 0;
  margin-right: 15px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-container,
  .search-filter {
    flex-direction: column;
    gap: 20px;
    align-items: flex-start;
  }

  .stats {
    gap: 20px;
  }

  .stat {
    margin-right: 0;
  }

  .search-box {
    width: 100%;
  }

  .order-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .products-grid {
    grid-template-columns: 1fr;
  }

  .order-product-thumbs-container {
    max-width: 100%;
    margin-top: 10px;
  }
}
</style>
